import { Linking, NetInfo, Settings, Dimensions } from 'react-native';
import DeviceInfo from 'react-native-device-info';
import Toast from 'react-native-root-toast';
import update from 'immutability-helper';
import { setLoginToken, setPickupCalenderId, setDeliveryCalenderId,
  getPickupCalenderId, getDeliveryCalenderId, getLoginToken } from './clientStorage';
import { NavigationActions } from 'react-navigation'
import moment from 'moment';
import getDirections from 'react-native-google-maps-directions';

export const screenWidth = Dimensions.get('window').width;
export const screenHeight = Dimensions.get('window').height;
export const primaryColor = '#FF7043';
// export const HOST = 'http://127.0.0.1:18080';
export const HOST = 'https://www.knocknockapp.com';

export function isLaundryOrder(type) {
  return ['laundry', 'premiumlaundry', 'curtainlaundry', 'carpetlaundry', 'bulkylaundry', 'loadwash'].indexOf(type)>=0;
}

export function getDirection({ status, shipping, pickup, delivery }) {
  if (!shipping) {
    shipping = isPickupOrder(status.statusId)?pickup:delivery;
  }

  const data = {
    params: [
      {
        key: "saddr",
        value: "my location"
      },
      {
        key: 'daddr',
        value: `${shipping.postalCode}`
      }
    ]
  };

  getDirections(data)
}

export function uploadImage(uri) {
  return new Promise((resolve, reject) => {
    getLoginToken()
      .then(token => {
        // format the image data 
        const imageDate = {
          uri,
          type: 'image/jpeg',
          name: uri.slice(uri.lastIndexOf('/')+1)
        };
        // Instantiate a FormData() object
        const imgBody = new FormData();
        // append the image to the object with the title 'image'
        imgBody.append('image', imageDate);
        // Perform the request. Note the content type - very important
        fetch(`${HOST}/upload`, {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'multipart/form-data',
              'authorization': `Bearer ${token}`
            },
            body: imgBody
          })
          .then(res => res.json())
          .then(res => resolve(res))
          .catch(error => resolve({}));
      });
  });
}

export function isPickupOrder(statusId) {
  return [1,2,3,4,10,12,9].indexOf(statusId)>=0;
}

export function isIOS() {
  return DeviceInfo.getSystemName()==='iOS';
}

export function launchAppMarket() {
  let link;
  if (DeviceInfo.getSystemName()==='iOS') {
    link = 'itms-apps://itunes.apple.com/us/app/id979512618?mt=8';
  } else {
    link = 'https://play.google.com/store/apps/details?id=com.knocknock.laundry';
  }
  Linking.canOpenURL(link).then(supported => {
    supported && Linking.openURL(link);
  }, (err) => console.log(err));
}

export function calculateInsurancePrice({dry,dryD,wash,washD,iron,ironD,dryCount=0,washCount=0,ironCount=0,insurance=0}, config) {
  if (!config||!(insurance>0)) return 0;

  const totalCount = dryCount+washCount+ironCount;
  const totalPrice = (dryD||dry)*dryCount+(washD||wash)*washCount+(ironD||iron)*ironCount;
  return parseFloat(Math.max(0, (parseFloat(insurance)*parseInt(totalCount) - parseFloat(totalPrice)*parseFloat(config.insuranceMultiple)) * parseFloat(config.esuranceCharge)).toFixed(2));
}

export function checkIsOldVersion(serverVersion) {
  const version = DeviceInfo.getVersion();

  const versionCodes = version.split('.');
  const serverVersionCodes = serverVersion.split('.');

  const serverMajor = parseInt(serverVersionCodes[0]);
  const serverMinor = parseInt(serverVersionCodes[1]);
  const serverTrivial = parseInt(serverVersionCodes[2]);

  const localMajor = parseInt(versionCodes[0]);
  const localMinor = parseInt(versionCodes[1]);
  const localTrivial = parseInt(versionCodes[2]);

  if (serverMajor>localMajor
    || ((serverMajor===localMajor)&&(serverMinor>localMinor))
    || ((serverMajor===localMajor)&&(serverMinor===localMinor)&&(serverTrivial>localTrivial))) {
    return true;
  }
}

export function processSuccessLogin({ token }, screenProps, navigation, page) {
  return setLoginToken(token)
    .then(() => {
      screenProps.resetStore();
      navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({routeName: page})
        ]
      }));
    });
}

export function loadMoreData(fetchMore, datas, dataKey) {
  return fetchMore({
    variables: {
      offset: datas.length
    },
    updateQuery: (previousResult, { fetchMoreResult }) => {
      if (!fetchMoreResult) return previousResult;

      if (fetchMoreResult[dataKey].length === 0) toast('All data loaded');

      return update(previousResult, {
        [dataKey]: {
          $push: fetchMoreResult[dataKey]
        }
      });
    },
  });
}

export function checkoutNextPage(navigation, args) {
  const { stepper, stepIndex } = navigation.state.params;
  const nextStep = stepper[stepIndex+1];

  navigation.navigate(nextStep, {...navigation.state.params, ...args, stepIndex: stepIndex+1});
}

export function displayInChinese() {
  if (DeviceInfo.getDeviceLocale().indexOf('zh')===0) {
    return true;
  } else {
    return false;
  }
}

export function executor(submitFuc, args) {
  return new Promise((resolve, reject) => {
    submitFuc(args)
      .then(response => resolve({res: response.data}))
      .catch(({message, graphQLErrors}) => {
        console.log(graphQLErrors);
        if (graphQLErrors&&graphQLErrors[0]&&graphQLErrors[0].message) {
          message = graphQLErrors[0].message;
        }
        if (message) {
          toast(message);
        }
        resolve({err: message});
      });
  })
}

export function hasNewVersion(serverVersion) {
  const version = DeviceInfo.getVersion();
  const versionCodes = version.split('.');
  const serverVersionCodes = serverVersion.split('.');

  const serverMajor = parseInt(serverVersionCodes[0]);
  const serverMinor = parseInt(serverVersionCodes[1]);
  const serverTrivial = parseInt(serverVersionCodes[2]);

  const localMajor = parseInt(versionCodes[0]);
  const localMinor = parseInt(versionCodes[1]);
  const localTrivial = parseInt(versionCodes[2]);

  if (serverMajor>localMajor
    || ((serverMajor===localMajor)&&(serverMinor>localMinor))
    || ((serverMajor===localMajor)&&(serverMinor===localMinor)&&(serverTrivial>localTrivial))) {
    return true;
  } else {
    return false;
  }
}

function getErrorMesssage({source}) {
  if (source&&source.data&&source.errors&&source.errors.length>0) {
    return source.errors[0].message;
  }
}

export function toast(message, long) {
  if (message.message) {
    message = message.message;
  } else if (message instanceof Object) {
    message = JSON.stringify(message);
  }
  
  Toast.show(message, {
    duration: long?Toast.durations.LONG:Toast.durations.SHORT,
    position: Toast.positions.CENTER,
    shadow: true,
    animation: true,
  });
}

function networkToast() {
  toast(displayInChinese()?'没有可用的网络链接，请检查您的网络链接设置':'None connection found, please check your network connection');
}

function isConnected() {
  return NetInfo.isConnected.fetch();
}

